package my.diplom.web.controllers;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.validation.Errors;
import org.springframework.validation.BindException;
import org.apache.log4j.Logger;
import com.octo.captcha.service.image.ImageCaptchaService;
import my.diplom.dao.service.UserService;
import my.diplom.dao.service.RoleService;
import my.diplom.dao.service.StatusService;
import my.diplom.entity.User;
import my.diplom.entity.Role;
import my.diplom.entity.Status;
import my.diplom.util.MailUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.List;
import java.util.HashMap;
import java.beans.PropertyEditorSupport;

/**
 * Created by IntelliJ IDEA.
 * User: gb
 * Date: 06.08.2009
 * Time: 0:28:44
 * To change this template use File | Settings | File Templates.
 */
public class UserController extends SimpleFormController{

    private static final Logger log = Logger.getLogger(RegisterController.class);

    private UserService userService;
    private RoleService roleService;
    private StatusService statusService;



    public UserController() {
        setCommandClass(User.class);
        setCommandName("newUser");
        setSessionForm(false);
        setBindOnNewForm(false);
    }


    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    public void setStatusService(StatusService statusService) {
        this.statusService = statusService;
    }

  


    @Override
    protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
        List<User> users = userService.getAll();
        List<Role> roles = roleService.getAll();
        HashMap<String, Object> model = new HashMap<String, Object>();
        model.put("users", users);
        model.put("allRoles", roles);
        return model;
    }

    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
        User user = (User) command;
        userService.create(user);
        log.debug("create new user " + user.getFirstName() + user.getLastName());
        return new ModelAndView(new RedirectView("createUser.htm"));
    }


    @Override
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        if (request.getParameter("userId") != null && request.getParameter("action").equals("edit")){
            User user = userService.getById(Long.parseLong(request.getParameter("userId")));
            return user;
        }
        User user = new User();
        return user;
    }



    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
          binder.registerCustomEditor(Status.class, "status", new PropertyEditorSupport() {

            public void setAsText(String text) {
                if (text instanceof String) {
                    if (text.equals("inactive")) {
                        Status status = statusService.getByName("inactive");
                        setValue(status);
                    } else if (text.equals("active")) {
                        Status status = statusService.getByName("active");
                        setValue(status);
                    }

                }
            }

            public String getAsText() {
                Object value = getValue();
                if (value != null) {
                    Status status = (Status) value;
                    return status.getStatusName();
                }
                return null;
            }


        });

        binder.registerCustomEditor(Role.class, "role", new PropertyEditorSupport() {

            public void setAsText(String text) {
                if (text instanceof String) {
                   Long roleId = Long.parseLong(text);
                    Role role = roleService.getById(roleId);
                    setValue(role);
                }
            }

            public String getAsText() {
                Object value = getValue();
                if (value != null) {
                    Role role = (Role) value;
                    return role.getRoleName();
                }
                return null;
            }


        });


     }




}
